package com.demo.kotlin.ui.main

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.blankj.utilcode.util.ActivityUtils
import com.demo.kotlin.R
import com.demo.kotlin.databinding.ActivityMainBinding
import com.demo.kotlin.ui.framework.FrameworkFragment
import com.demo.kotlin.ui.home.HomeFragment
import com.demo.kotlin.ui.mine.LoginActivity
import com.demo.kotlin.ui.mine.MineFragment
import com.demo.kotlin.ui.performance.PerformanceFragment
import com.demo.kotlin.ui.zdykj.WidgetsFragment
import com.puhui.lib.base.BaseActivity
import com.puhui.lib.widgets.indicator.MainTabIndicator
import com.puhui.lib.widgets.indicator.TabObject

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private var lastBackClickTime: Long = 0 //上次点击返回键时间戳

    private var selectTabId: String? = null
    private var mCurrentFragment: MainTabFragment<*, *>? = null
    private var mFragmentMap: MutableMap<String, MainTabFragment<*, *>?> = mutableMapOf()

    companion object {
        private const val KEY_SELECTED_TAB_ID = "key_selected_tab_id"

        @JvmStatic
        fun back2Main(activity: Activity, tabId: String) {
            val intent = Intent(activity, MainActivity::class.java)
            intent.putExtra("tab_id", tabId)
            activity.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun init(savedInstanceState: Bundle?) {

        initBottomTab(savedInstanceState)
    }

    private fun initBottomTab(savedInstanceState: Bundle?) {
        val tabObjects: MutableList<TabObject> = mutableListOf()
        tabObjects.add(TabObject(R.string.tab_first, R.drawable.tab_indicator_one, HomeFragment::class.java.name))
        tabObjects.add(TabObject(R.string.tab_second, R.drawable.tab_indicator_two, FrameworkFragment::class.java.name))
        tabObjects.add(TabObject(R.string.tab_third, R.drawable.tab_indicator_three, PerformanceFragment::class.java.name))
        tabObjects.add(TabObject(R.string.tab_fourth, R.drawable.tab_indicator_four, WidgetsFragment::class.java.name))
        tabObjects.add(TabObject(R.string.tab_fifth, R.drawable.tab_indicator_five, MineFragment::class.java.name))
        mContentView.mainTabIndicator.initData(tabObjects)
        mContentView.mainTabIndicator.setOnTabClickListener(object : MainTabIndicator.TabClickListener {
            override fun onTabSelected(tabObj: TabObject): Boolean {
                if (mFragmentMap[tabObj.tabClassName]?.needUserLogin() == true) {
                    startActivity(LoginActivity::class.java)
                    return false
                }
                return true
            }
        })

        var firstFragment: MainTabFragment<*, *>? = null
        // 用户开启“不保留活动”，需要保存Activity状态
        savedInstanceState?.let {
            selectTabId = it.getString(KEY_SELECTED_TAB_ID)
            val mFragmentManager = supportFragmentManager
            val fragmentTransaction = mFragmentManager.beginTransaction()
            for (index in tabObjects.indices) {
                val tabClassName = tabObjects[index].tabClassName
                val savedFragment = mFragmentManager.findFragmentByTag(tabClassName)
                if (savedFragment is MainTabFragment<*, *>) {
                    //一句话解决应用崩溃重启后，fragment重叠问题
                    if (savedFragment.isAdded) fragmentTransaction.hide(savedFragment)

                    if (tabClassName == selectTabId) {
                        //如果缓存的当前fragmentTag有值，则取缓存的当前页面；否则取第一个页面为默认值
                        firstFragment = savedFragment
                    } else if (index == 0) {
                        selectTabId = tabClassName
                        firstFragment = savedFragment
                    }
                    mFragmentMap[tabClassName] = savedFragment
                }
            }
            fragmentTransaction.commit()
        }

        for (index in tabObjects.indices) {
            val tabClassName = tabObjects[index].tabClassName
            if (mFragmentMap[tabClassName] == null) {
                val tabClazz = Class.forName(tabClassName)
                val obj = tabClazz.newInstance()
                if (obj is MainTabFragment<*, *>) {
                    if (tabClassName == selectTabId) {
                        //如果缓存的当前fragmentTag有值，则取缓存的当前页面；否则取第一个页面为默认值
                        firstFragment = obj
                    } else if (index == 0) {
                        selectTabId = tabClassName
                        firstFragment = obj
                    }
                    mFragmentMap[tabClassName] = obj
                }
            }
        }

        firstFragment?.let { changeCurrentFragment(it, selectTabId) }
    }

    private fun changeCurrentFragment(fragment: MainTabFragment<*, *>, tabId: String?) {

        val mFragmentManager = supportFragmentManager
        val fragmentTransaction = mFragmentManager.beginTransaction()
        val className = fragment.javaClass.name

        mCurrentFragment?.let {
            //在当前缓存的Fragment不为空的前提下，判断传入的fragment是否和当前缓存的实例相同
            //为什么作此判断？，fragment.isAdded()在已经add过的前提下依然返回false，导致又add一次，造成重影问题，所以作此判断提前截断
            if (javaClass.name == className) return@changeCurrentFragment
            fragmentTransaction.hide(it)
        }

        if (fragment.isAdded) {
            fragmentTransaction.show(fragment)
        } else if (mFragmentManager.findFragmentByTag(className) == null) {
            fragmentTransaction.add(R.id.contentLayout, fragment, className)
        }
        fragmentTransaction.commit()
        mCurrentFragment = fragment
        selectTabId = tabId
        setStatusBarColor(mCurrentFragment)
    }

    private fun setStatusBarColor(currentFragment: MainTabFragment<*, *>?) {
        currentFragment?.apply {
            setStatusBar(getStatusBarColor(), isFullScreen(), isLightMode())
        }
    }

    /**
     * @param outState 当用户开启"不保留活动或者正常被系统回收时，保存当前选中的Fragment"
     * 再次恢复时，可以避免Fragment重影
     */
    override fun onSaveInstanceState(outState: Bundle) {
        outState.putString(KEY_SELECTED_TAB_ID, selectTabId)
        super.onSaveInstanceState(outState)
    }

    /**
     * 点击返回键
     */
    override fun onBackPressed() {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastBackClickTime < 2000) {
            ActivityUtils.finishAllActivities()
        } else {
            showToast("再点一次退出")
            lastBackClickTime = currentTime
            return
        }
        return super.onBackPressed()
    }
}